package org.example.day1;

import java.sql.Connection;

public class JDBC_Demo {
    //加载JDBC-MySQL数据库驱动
    static {
        try {
            //mysql版本是8以上，那么加载驱动包：com.mysql.cj.jdbc.Driver
            //mysql版本是5，那么加载驱动包：com.mysql.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //连接数据库
    public static void main(String[] args) {
        Connection conn = null;
        try {
            String url = "jdbc:mysql://172.18.92.57:3306/javaweb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
            String user = "rjgc21";
            String password = "rjgc21";
            //获取数据库连接对象-Connection对象
            conn = java.sql.DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功！");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //得到SQL查询语句对象
        java.sql.Statement stmt = null;
        try {
            stmt = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //执行SQL查询语句
        try {
            java.sql.ResultSet rs = stmt.executeQuery("select * from user");
            //遍历结果集
            while (rs.next()) {
                System.out.println(rs.getString("username"));
                System.out.println(rs.getString("password"));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //关闭连接
        try {
            conn.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

